package com.csnj.common.biz;

import com.csnj.common.utils.EntityUtils;
import com.csnj.common.utils.ReflectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.csnj.common.entity.APIResult;
import com.csnj.common.entity.Query;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Created by Mr.AG
 * Date: 17/1/13
 * Time: 15:13
 * Version 1.0.0
 * 基础业务类封装, 封装mybatis生成的实体对象类
 */
public abstract class BaseBiz<M extends Mapper<T>, T> {
    @Autowired
    protected M mapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public void setMapper(M mapper) {
        this.mapper = mapper;
    }

    public T selectOne(T entity) {
        return mapper.selectOne(entity);
    }


    public T selectById(Object id) {
        return mapper.selectByPrimaryKey(id);
    }


    public List<T> selectList(T entity) {
        return mapper.select(entity);
    }


    public List<T> selectListAll() {
        return mapper.selectAll();
    }


    public Long selectCount(T entity) {
        return new Long(mapper.selectCount(entity));
    }


    public void insert(T entity) {
        try{
            EntityUtils.setCreatAndUpdatInfo(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapper.insert(entity);
    }


    public void insertSelective(T entity) {
        try{
            EntityUtils.setCreatAndUpdatInfo(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapper.insertSelective(entity);
    }

    public CompletableFuture<Void> insertSelectiveAsync(T entity) {
        return CompletableFuture.runAsync(() -> {
            mapper.insertSelective(entity);
        });
    }


    public void delete(T entity) {
        mapper.delete(entity);
    }


    public void deleteById(Object id) {
        mapper.deleteByPrimaryKey(id);
    }

    public CompletableFuture<Void> deleteByIdAsync(Object id) {
        return CompletableFuture.runAsync(() -> {
            mapper.deleteByPrimaryKey(id);
        });
    }


    public void updateById(T entity) {
        try {
            EntityUtils.setUpdatedInfo(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapper.updateByPrimaryKey(entity);
    }


    public void updateSelectiveById(T entity) {
        try {
            EntityUtils.setUpdatedInfo(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapper.updateByPrimaryKeySelective(entity);
    }

    public CompletableFuture<Void> updateSelectiveByIdAsync(T entity) {
        return CompletableFuture.runAsync(() -> {
            mapper.updateByPrimaryKeySelective(entity);
        });
    }

    public List<T> selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    public int selectCountByExample(Object example) {
        return mapper.selectCountByExample(example);
    }

    public APIResult selectByQuery(Query query) {
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        Example.Criteria criteria = example.createCriteria();
        if(query.entrySet().size()>0) {
            for (Map.Entry<String, Object> entry : query.entrySet()) {
                criteria.andEqualTo(entry.getKey(), entry.getValue());
            }
        }
        if(query.getKey()!=null) {
            String strKeys = EntityUtils.getStringKeys(clazz);
            String sqlgram = "CONCAT_WS(\" \"," + strKeys.substring(0, strKeys.length()-1) + ") like \"%" + query.getKey() + "%\"";
            criteria.andCondition(sqlgram);
        }
        if(ReflectionUtils.ClassHasField(clazz, "updateTime")) {
            example.setOrderByClause("update_time desc");
        } else if(ReflectionUtils.ClassHasField(clazz, "createTime")) {
            example.setOrderByClause("create_time desc");
        }
        Page<Object> result = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<T> list = mapper.selectByExample(example);
        return new APIResult(new PageInfo(list));
    }

    public CompletableFuture<Integer> insertBatchDataAsync(List<T> entitys) {
        return CompletableFuture.supplyAsync(() -> {
            SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
            try{
                Class<M> clazz = (Class<M>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
                M batchMapper = session.getMapper(clazz);
                for(T entity: entitys) {
                    batchMapper.insertSelective(entity);
                }
                session.commit();
                session.clearCache();
            } finally {
                session.close();
            }
            return entitys.size();
        });
    }
}
